import React from 'react';
import { connect } from 'dva';
import * as service from '../services';
import TimeInterval from '@/components/TimeInterval'
import { toThousands } from '@/utils/util'
import style from './node.less';


class NodeInfo extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    this.socket = service.listenSocket((data) => {
      this.props.dispatch({ type: 'node/save', payload: { data } })
    });
  }

  componentWillUnmount() {
    this.socket.close();
    this.props.dispatch({ type: 'node/reset' })
  }

  render() {
    const data = this.props.list;
    const nodes = data ? data.map((node, index) => {
      return (
        <tr key={index} className={Date.now() - node.received_time > 30000 ? style.red : null}>
          <td><div><span>{node.node_name}</span></div></td>
          <td><div><span>{node.node_ip}</span></div></td>
          <td><div><span>{node.version}</span></div></td>
          <td><div><span>{node.conn_num}</span></div></td>
          <td><div><span>{toThousands(node.latest_block)}</span></div></td>
          <td><div><span>{node.latest_block_hash.substring(0, 10) + '...' + node.latest_block_hash.substring(node.latest_block_hash.length - 8)}</span></div></td>
          <td><div><span><TimeInterval past={node.received_time - node.latest_block_time} beginTime={node.received_time} lang='en'/></span></div></td>
          <td><div><span>{node.broadcast_time + 'ms'}</span></div></td>
          <td><div><span>{node.avg_broadcast_time + 'ms'}</span></div></td>
          <td><div><span>{node.is_producer ? '√': ''}</span></div></td>
          <td><div><span>{node.pending_transactions}</span></div></td>
        </tr>
      );
    }) : null;

    return (
      <div className={style.normal}>
        <table className={style.info}>
          <thead>
          <tr>
            <td><div><span>节点名</span></div></td>
            <td><div><span>节点IP</span></div></td>
            <td><div><span>运行版本</span></div></td>
            <td><div><span>连接数</span></div></td>
            <td><div><span>最新区块</span></div></td>
            <td><div><span>最新区块哈希</span></div></td>
            <td><div><span>最新区块时间</span></div></td>
            <td><div><span>区块广播时间</span></div></td>
            <td><div><span>平均区块广播时间</span></div></td>
            <td><div><span>出块委员会</span></div></td>
            <td><div><span>待处理交易</span></div></td>
          </tr>
          </thead>
          <tbody>
          {nodes}
          </tbody>
        </table>
      </div>
    )
  }

}

function mapStateToProps(state) {
  const { list } = state.node;
  return {
    list,
  };
}

export default connect(mapStateToProps)(NodeInfo);
